//
//  BaseWebViewController.m
//

#import "BaseWebViewController.h"
#import <WebKit/WebKit.h>
#import <StoreKit/StoreKit.h>
#import <StoreKit/SKStoreReviewController.h>

@interface BaseWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic) WKWebView *webView;

@end

@implementation BaseWebViewController

- (void)back{
    if (self.webView.canGoBack == YES) {
        [self.webView goBack];
        return;
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [CreaditUtilsHelper hideLoadMessageBox];
    [CreaditUtilsHelper hideLoadMessageBoxFromView:self.webView];
}

- (WKWebView *)webView {
    if (!_webView) {
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = [WKUserContentController new];
        
        NSArray *methodArr = @[@"quiltVani",@"irisQuinc",@"whaleGira",@"saficanty",@"nutQuince",@"kaleZucch"];
        [methodArr enumerateObjectsUsingBlock:^(NSString *methodStr, NSUInteger idx, BOOL * _Nonnull stop) {
            [config.userContentController addScriptMessageHandler:self name:methodStr];
        }];
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preferences;
 
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        _webView.allowsBackForwardNavigationGestures = YES;

    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavigationBarHeight);
    
    [self.view addSubview:self.webView];

    [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.webView];
    
//    NSString *urlStr = [self.urlStr stringByAppendingFormat:@"?meal=%@&warmed=%@&boyfine=%@&inquiring=%@&kitchen=%@&duty=%@&cheerless=%@&blazed=%@",@"ios",@"mmla",@"common",kAppVersion,esString([[UIDevice currentDevice] name]),esString([UIDevice currentDevice].systemVersion),esString([[UIDevice currentDevice] identifierForVendor].UUIDString),esString([[UIDevice currentDevice] identifierForVendor].UUIDString)];
//
//    if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
//        urlStr = [urlStr stringByAppendingFormat:@"&brightly=%@",esString([CurrentUser mine].sessionKey)];
//    }
//
//    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
   
    NSURL *url = [NSURL URLWithString:esString(self.urlStr)];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0f]];
}

#pragma mark - - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [CreaditUtilsHelper hideLoadMessageBox];
    [CreaditUtilsHelper hideLoadMessageBoxFromView:self.webView];
//    if (webView.title.length > 0) {
//        self.title = webView.title;
//    }
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (error == nil) {
            if (result != nil) {
                self.title = [NSString stringWithFormat:@"%@",esString(result)];
            }
        }
    }];

}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error{
    [CreaditUtilsHelper hideLoadMessageBox];
    [CreaditUtilsHelper hideLoadMessageBoxFromView:self.webView];
}

- (void) webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction*) navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    DLog(@"====absoluteString=======%@",navigationAction.request.URL.absoluteString);
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WKScriptMessageHandler
//h5->app
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    
//    NSString *jsonString= message.body;
//    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//    NSError *error;
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
//    NSDictionary *dic = [NSString dictionaryWithJsonString:message.body];
    
    id body = message.body;
    
    if ([message.name isEqualToString:@"quiltVani"]){
        DLog(@"===%@",body);
        
        if (isArray(body)) {
            NSArray *ary = body;
            [CreditServerHelper uploadMaiDianDataStartTimeStr:self.startTimeStr andEndTimeStr:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] withTypeStr:@"10" withFirmly:ary.firstObject withSmaller:ary.lastObject];
        }
        
    }
    else if ([message.name isEqualToString:@"irisQuinc"]){
        DLog(@"===%@",body);
        [[CreditCore globleCore] jumpToPage:body];
    }
    else if ([message.name isEqualToString:@"nutQuince"]){
        DLog(@"===%@",body);
        NSString *str = body;

        if ([str containsString:@"tel:"]) {
            str = [str substringFromIndex:4];
            [StringUtil telephoneCall:str];
        }
        else if ([str containsString:@"email:"]) {
            str = [str substringFromIndex:6];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@",str]] options:@{} completionHandler:^(BOOL success) {
            }];
        }
        else if ([str containsString:@"copy:"]) {
            str = [str substringFromIndex:5];
            [UIPasteboard generalPasteboard].string = esString(str);
            [CreaditUtilsHelper boxShowWithMessage:@"Copied successfully"];
        }
        
    }
    else if ([message.name isEqualToString:@"kaleZucch"]){
        DLog(@"====%@",body);
        [SKStoreReviewController requestReview];
    }
    else if ([message.name isEqualToString:@"whaleGira"]){
        DLog(@"===%@",body);
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else if ([message.name isEqualToString:@"saficanty"]){
        DLog(@"===%@",body);
        [self.navigationController popToRootViewControllerAnimated:NO];
        [self.tabBarController setSelectedIndex:0];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Sss" object:nil userInfo:@{@"index":@"1"}];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

